package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"src/fileformat"
	"strings"
)

var (
	h       bool
	dst_dir string
)

func init() {
	flag.BoolVar(&h, "h", false, "help msg")
	flag.StringVar(&dst_dir, "d", ".", "dst fmt dir")
	flag.Usage = usage
}

func main() {
	flag.Parse()

	if h {
		flag.Usage()
		return
	}

	formatDir(dst_dir)
}

func usage() {
	fmt.Fprintf(os.Stderr, "cfmt \nUsage:cfmt [-h] [-d dst_dir] \nOptions:")
	flag.PrintDefaults()
}

func formatDir(dir string) {
	fileinfo, err := ioutil.ReadDir(dir)

	if err != nil {
		log.Fatal("readdir failed ", dir, " err=", err)
	}

	for _, file := range fileinfo {
		filename := dir + "/" + file.Name()
		if file.IsDir() {
			formatDir(filename)
			continue
		}
		if strings.HasSuffix(file.Name(), ".c") ||
			strings.HasSuffix(file.Name(), ".h") {
			dst := fileformat.NewFileFormat(filename)
			dst.Format()
			continue
		}
	}
}
